#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
import matplotlib
matplotlib.use('cairo.pdf')
from matplotlib import pyplot

import cPickle as pickle
import sys


def compute_scatter_data(top10kfylname, portsfylname):
  top10k = pickle.load(open(top10kfylname, 'r'))
  ports = dict(pickle.load(open(portsfylname, 'r')))

  scatterdat = [(ports[ip], torrents, ip) for (ip, torrents) in top10k]
  return scatterdat


fylname = 'top10scatter.dat'
def make_scatter(top10kfylname, portsfylname):
  try:
    data = pickle.load(open(fylname, 'r'))
  except IOError:
    data = compute_scatter_data(top10kfylname, portsfylname)
    pickle.dump(data, open(fylname, 'w'), pickle.HIGHEST_PROTOCOL)

  print len(data)
  data = list(frozenset(x[:2] for x in data))
  print len(data)
  xd = [x[0] for x in data]
  yd = [x[1] for x in data]
  pyplot.plot(xd, yd, linestyle='None', marker='.', markersize=1, color='k')
  pyplot.xlim(xmin=0)
  pyplot.ylim(ymin=0)
  pyplot.title('Torrents vs. # of ports for the top 10,000 IPs')
  pyplot.xlabel('Ports used by IP')
  pyplot.ylabel('Torrents IP joined (#)')

#  inset_ax = pyplot.axes([.525, .15, .35, .4])
#  pyplot.plot(xd, yd, linestyle='None', marker='.', color='k')
#  pyplot.xlim(xmin=0, xmax=250)
#  pyplot.ylim(ymin=0, ymax=1600)
  pyplot.savefig('top10kscatter.pdf')

if __name__ == '__main__':
  make_scatter(sys.argv[1], sys.argv[2])
